<template>
  <el-dialog
    v-model="show"
    :width="modalOptions.width"
    :title="modalOptions.title"
    :close-on-click-modal="false"
    :align-center="false"
    render-to-body
  >
    <div class="py-24 px-12">
      <slot :show="show"></slot>
    </div>

    <template #footer>
      <slot v-if="$slots.footer" name="footer"></slot>

      <footer v-else-if="modalOptions.showFooter">
        <el-space>
          <el-button @click="handleCancel" v-if="modalOptions.showCancel">
            {{ modalOptions.cancelText }}
          </el-button>
          <el-button
            style="width: 80px"
            type="primary"
            :loading="okLoading"
            v-if="modalOptions.showOk"
            @click="handleOK"
          >
            {{ modalOptions.okText }}
          </el-button>
        </el-space>
      </footer>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
const props = defineProps({
  width: {
    type: String,
    default: "800px",
  },
  title: {
    type: String,
    default: "",
  },
  closable: {
    type: Boolean,
    default: true,
  },
  cancelText: {
    type: String,
    default: "取消",
  },
  okText: {
    type: String,
    default: "确定",
  },
  showFooter: {
    type: Boolean,
    default: true,
  },
  showCancel: {
    type: Boolean,
    default: true,
  },
  showOk: {
    type: Boolean,
    default: true,
  },
  modalStyle: {
    type: Object,
    default: () => {},
  },
  contentStyle: {
    type: Object,
    default: () => {},
  },
  onOk: {
    type: Function,
    default: () => {},
  },
  onCancel: {
    type: Function,
    default: () => {},
  },
});

const show = ref(false);
const modalOptions = ref({ ...props });
function open(options = {}) {
  modalOptions.value = { ...props, ...options };

  show.value = true;
}
function close() {
  show.value = false;
}

async function handleOK(data?: any) {
  if (typeof modalOptions.value.onOk !== "function") {
    return close();
  }
  try {
    // 调用onOk函数，传入data参数
    const res = await modalOptions.value.onOk(data);
    // 如果onOk函数的返回值不为false，则关闭模态框
    res !== false && close();
  } catch (error) {
    debugger;
    okLoading.value = false;
    console.error(error);
  }
}

async function handleCancel(data?: any) {
  if (typeof modalOptions.value.onCancel !== "function") {
    return close();
  }
  try {
    // 调用onCancel函数，传入data参数
    const res = await modalOptions.value.onCancel(data);

    // 如果onCancel函数的返回值不为false，则关闭模态框
    res !== false && close();
  } catch (error) {
    okLoading.value = false;
    console.error(error);
  }
}

const okLoading = computed({
  get() {
    return !!modalOptions.value?.okLoading;
  },
  set(v: boolean) {
    if (modalOptions.value) {
      modalOptions.value.okLoading = v;
    }
  },
});

defineExpose({
  open,
  close,
  show,
  handleOK,
  handleCancel,
  okLoading,
  options: modalOptions,
});
</script>

<style scoped lang="less"></style>
